<template>
  <transition name="v-zoom-in-top" @after-leave="doDestroy">
    <div
      v-show="showPopper"
      class="v-autocomplete-suggestion"
      :class="{ 'is-loading': parent.loading }"
      :style="{ width: dropdownWidth }"
    >
      <v-scrollbar
        tag="ul"
        wrap-class="v-autocomplete-suggestion__wrap"
        view-class="v-autocomplete-suggestion__list"
      >
        <li v-if="parent.loading">
          <v-spinner color="#1a9bff" name="spin" :size="24"></v-spinner>
        </li>
        <template v-for="(item, index) in suggestions" v-else>
          <li
            v-if="!parent.customItem"
            :class="{'highlighted': parent.highlightedIndex === index}"
            @click="select(item)"
          >
            {{item[props.label]}}
          </li>
          <component
            v-else
            :class="{'highlighted': parent.highlightedIndex === index}"
            @click="select(item)"
            :is="parent.customItem"
            :item="item"
            :index="index">
          </component>
        </template>
      </v-scrollbar>
    </div>
  </transition>
</template>
<script>
  import Popper from '@/vuego/utils/vue-popper';
  import Emitter from '@/vuego/mixins/emitter';
  import VScrollbar from '@/vuego/components/v-scrollbar/v-scrollbar';
  import VSpinner from '@/vuego/components/v-spinner/v-spinner';

  export default {
    components: { VScrollbar, VSpinner },
    mixins: [Popper, Emitter],
    componentName: 'VAutocompleteSuggestions',
    data() {
      return {
        parent: this.$parent,
        dropdownWidth: '',
      };
    },
    props: {
      props: Object,
      suggestions: Array,
      options: {
        default() {
          return {
            forceAbsolute: true,
            gpuAcceleration: false,
          };
        },
      },
    },
    methods: {
      select(item) {
        this.dispatch('VAutocomplete', 'item-click', item);
      },
    },
    updated() {
      this.$nextTick(() => {
        this.updatePopper();
      });
    },
    mounted() {
      this.popperElm = this.$el;
      this.$parent.popperElm = this.popperElm;
      this.referenceElm = this.$parent.$refs.input.$refs.input;
    },
    created() {
      this.$on('visible', (val, inputWidth) => {
        this.dropdownWidth = `${inputWidth}px`;
        this.showPopper = val;
      });
    },
  };
</script>
